const { Op } = require("sequelize");
const Cart = require("../model/cart.model");
const Goods = require("../model/goods.model");

class CartService {
    async createOrUpdate(user_id, goods_id) {
        const res = await Cart.findOne({
            where: {
                [Op.and]: {
                    user_id,
                    goods_id,
                },
            },
        });

        //已经存在记录,number+1
        if (res) {
            await res.increment("number", { by: 1 });
            //调用Sequelize方法返回更新后的值
            return await res.reload();
        } else {
            return await Cart.create({
                user_id,
                goods_id,
            });
        }
    }

    async findCarts(pageNum, pageSize, goods_name) {
        const offset = (pageNum - 1) * pageSize;
        const { count, rows } = await Cart.findAndCountAll({
            attributes: ["id", "number", "selected"], //要哪些字段
            offset: offset,
            limit: pageSize * 1,
            include: {
                //包含goods表,要与model的配置对应
                model: Goods,
                as: "goods_info", //要与model中的别名匹配。这里的as设置的是Goods模型的别名，即在查询结果中使用"goods_info"来访问Goods模型的属性。
                attributes: ["id", "goods_name", "goods_price", "goods_img"],
            },
        });
        return {
            pageNum: pageNum,
            pageSize: pageSize,
            total: count,
            list: rows,
        };
    }

    async updateCarts(params) {
        const { id, number, selected } = params;
        //返回模型对象，之后可以直接执行save方法
        const res = await Cart.findByPk(id);
        if (!res) return "";

        number !== undefined ? (res.number = number) : "";
        selected !== undefined ? (res.selected = selected) : "";
        return await res.save(res);
    }

    async removeCarts(ids) {
        return await Cart.destroy({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
        });
    }

    async selectAllCarts(user_id){
        return await Cart.update({selected: true}, {where: {
            user_id
        }})
    }

    async unselectAllCarts(user_id){
        return await Cart.update({selected: false}, {where: {
            user_id
        }})
    }

}

module.exports = new CartService();
